﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UtilTool
{
    class SqlHelper
    {
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        private static string connectionStr = "";

        /// <summary>
        /// 用来外部初始化
        /// </summary>
        /// <param name="connectionStr"></param>
        public SqlHelper(string connectionStr)
        {
            SqlHelper.connectionStr = connectionStr;
        }

        public SqlHelper()
        {
            connectionStr = System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        }
        /// <summary>
        /// 得到连接对象
        /// </summary>
        /// <returns></returns>
        public static SqlConnection GetConn()
        {
            SqlConnection sqlconn = null;
            sqlconn = new SqlConnection(connectionStr);
            return sqlconn;
        }

        /// <summary>
        /// 查询操作
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(string sql, params SqlParameter[] sp)
        {
            using (SqlConnection conn = GetConn())
            {
                conn.Open();
                using (SqlDataAdapter sda = new SqlDataAdapter(sql, conn))
                {
                    sda.SelectCommand.Parameters.AddRange(sp);
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    return dt;
                }
            }
        }

        /// <summary>
        /// 查询操作
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(string sql)
        {
            using (SqlConnection conn = GetConn())
            {
                conn.Open();
                using (SqlDataAdapter sda = new SqlDataAdapter(sql, conn))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
        /// <summary>
        /// 增删改操作
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns>执行后的条数</returns>
        public static int ExecuteQuery(string sql, params SqlParameter[] sp)
        {
            using (SqlConnection conn = GetConn())
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(sp);
                    int i = cmd.ExecuteNonQuery();
                    return i;
                }
            }

        }

        public static void ExecuteTran(string[] sql, params SqlParameter[] sp)
        {
            using (SqlConnection conn = GetConn())
            {
                conn.Open();
                SqlTransaction st = conn.BeginTransaction();
                try
                {
                    foreach (string s in sql)
                    {
                        SqlHelper.ExecuteQuery(s);
                    }
                    st.Commit();
                }
                catch (SqlException ee)
                {
                    st.Rollback();
                    throw ee;
                }
            }
        }

        /// <summary>
        /// 执行一条SQL语句,返回首行首列
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns>首行首列</returns>
        public static object ExecuteScalar(string sql, params SqlParameter[] sp)
        {
            using (SqlConnection conn = GetConn())
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(sp);
                    return cmd.ExecuteScalar();
                }
            }
        }

        public bool TestConn()
        {
            bool IsOk = true;

            using (SqlConnection conn = SqlHelper.GetConn())
            {
                try
                {
                    conn.Open();
                }
                catch (Exception)
                {
                    IsOk = false;
                }
                finally
                {
                    conn.Close();
                }
            }

            return IsOk;
        }

        #region 判断数据库是否存在
        /// <summary>
        /// 判断数据库是否存在
        /// </summary>
        /// <param name="db">数据库的名称</param>
        /// <param name="connKey">数据库的连接Key</param>
        /// <returns>true:表示数据库已经存在；false，表示数据库不存在</returns>
        public Boolean IsDBExist(string db, string connKey)
        {

            string connToMaster = System.Configuration.ConfigurationManager.ConnectionStrings[connKey].ToString();
            string createDbStr = " select * from master.dbo.sysdatabases where name " + "= '" + db + "'";

            DataTable dt = SqlHelper.GetDataTable(createDbStr);
            if (dt.Rows.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        #region 判断数据库中，指定表是否存在
        /// <summary>
        /// 判断数据库表是否存在
        /// </summary>
        /// <param name="db">数据库</param>
        /// <param name="tb">数据表名</param>
        /// <param name="connKey">连接数据库的key</param>
        /// <returns>true:表示数据表已经存在；false，表示数据表不存在</returns>
        public Boolean IsTableExist(string db, string tb, string connKey)
        {
            string connToMaster = System.Configuration.ConfigurationManager.ConnectionStrings[connKey].ToString();
            string createDbStr = "use " + db + " select 1 from  sysobjects where  id = object_id('" + tb + "') and type = 'U'";

            //在指定的数据库中  查找 该表是否存在
            DataTable dt = SqlHelper.GetDataTable(createDbStr);
            if (dt.Rows.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }

        }
        #endregion

        #region 创建数据库
        /// <summary>
        /// 创建数据库
        /// </summary>
        /// <param name="db">数据库名称</param>
        /// <param name="connKey">连接数据库的key</param>
        public void CreateDataBase(string db, string connKey)
        {
            //符号变量，判断数据库是否存在
            Boolean flag = IsDBExist(db, connKey);

            //如果数据库存在，则抛出
            if (flag == true)
            {
                throw new Exception("数据库已经存在！");
            }
            else
            {
                //数据库不存在，创建数据库
                string connToMaster = System.Configuration.ConfigurationManager.ConnectionStrings[connKey].ToString();
                string createDbStr = "Create database " + db;
                SqlHelper.ExecuteQuery(createDbStr);
            }

        }
        #endregion
    }
}
